import xeEutils from "xe-utils";
import {useInfoStore} from "@/stores/user";
import {Message} from "@arco-design/web-vue";

/*
 * $XEUtils 全局注册方法
 * toDateDiffText() 过去时间
 * randomData(min,max) 随机 min~min
 * */
export const XeFun = {
  getSrc(item) {
    const userData = useInfoStore();
    if (!item) return;
    const a = item.indexOf("//");
    if (a > -1) {
      return item;
    } else {
      return userData["userInfo"].imgUrl + item;
    }
  },
  CopyUrl(url) {
    let domInput = document.createElement("input");
    domInput.value = "//down.ioaol.cn/" + url;
    document.body.appendChild(domInput);  // 添加input节点
    domInput.select(); // 选择对象;
    document.execCommand("Copy"); // 执行浏览器复制命令
    Message.success(
        `下载链接复制成功！`,
    );
    domInput.remove();
  },
  getToken() {
    const user = JSON.parse(localStorage.getItem("user"));
    if (user) {
      return user.userInfo.token;
    } else {
      return null;
    }
  },
  DelToken() {
    localStorage.clear();
  },
  toDateDiffText(date) {
    let currDate = new Date(); // '2018-12-10 10:10:00'
    let dateDiff = xeEutils.getDateDiff(date, currDate);
    if (dateDiff.done) {
      if (dateDiff.time < 31536000000) {
        if (dateDiff.time < 2592000000) {
          if (dateDiff.time < 86400000) {
            if (dateDiff.time < 360000) {
              if (dateDiff.time < 60000) {
                if (dateDiff.time < 10000) {
                  return "刚刚";
                }
                return `${dateDiff.ss}秒之前`;
              }
              return `${dateDiff.mm}分钟之前`;
            }
            return `${dateDiff.HH}小时之前`;
          }
          return `${dateDiff.dd}天之前`;
        }
        return `${dateDiff.MM}个月之前`;
      }
      return `${dateDiff.yyyy}年之前`;
    }
    return "错误类型";
  },
  treeData(source, id, parentId, children) {
    let cloneData = JSON.parse(JSON.stringify(source));
    return cloneData.filter(father => {
      // 顶级过滤
      let branchArr = cloneData.filter(child => father[id] === child[parentId]);
      // 子级过滤
      branchArr.length > 0 ? father[children] = branchArr : "";
      return father[parentId] === 0;    // 如果第一层不是parentId=0，请自行修改
    });
  },
  treeOneData(source, id, parentId, children) {
    let cloneData = JSON.parse(JSON.stringify(source));
    return cloneData.filter(father => {
      // 顶级过滤
      let branchArr = cloneData.filter(child => father[id] === child[parentId]);
      // 子级过滤
      branchArr.length > 0 ? father[children] = branchArr : "";
      return father[parentId] === 1;    // 如果第一层不是parentId=0，请自行修改
    });
  }
};
